<?php

class FormElement_Images extends FormElement
{

  public $primaryKey;

  public $foreignKey;

  public $table;

  public $fields = array('filename' => 'image_filename', 'caption' => 'image_caption');

  public function beforeAction()
  {
    $this->remove = Form::ACTION_CREATE | Form::ACTION_INDEX;

    if (s::request()->get('formAction') == 'imagesDelete') {
      $pk = $this->getPrimaryKey();
      $id = s::request()->post($pk);

      $image = DB::getInstance()->query()->from($this->getTable())->where("$pk = :$pk")->execute(array($pk => $id))->fetchRow();

      $filename = $this->getFilesDir() . $image[$this->getFieldName('filename')];

      @unlink($filename);

      DB::getInstance()->delete($this->getTable(), "$pk = :$pk")->execute(array($pk => $id));

      $view = View::factory('Json');
      $view->set($pk, $id);
      echo $view->render();
      exit();
    }
    elseif (s::request()->get('formAction') == 'imagesCheckUpload') {
      $data = array();
      $view = View::factory('Json');
      $view->copyAll($data);
      echo $view->render();
      exit();
    }
    elseif (s::request()->get('formAction') == 'imagesUpload') {
      $data = array();

      if (! empty($_FILES['Filedata'])) {
        try {
          $upload = Component::factory('upload');
          $upload->getParameters()->set('hash_filename', true);
          $upload->upload('Filedata');

          $image = array(
            $this->getForeignKey() => $this->form->getId(),
            $this->getFieldName('filename') => $upload->getUploadedPath()
          );

          DB::getInstance()->insert($this->getTable(), $image)->execute($image);

          $image[$this->getPrimaryKey()] = DB::getInstance()->lastInsertId();

          $image['thumb_src'] = $this->getThumb($image[$this->getFieldName('filename')], 100, 100);
          $image['image_src'] = $this->getThumb($image[$this->getFieldName('filename')]);

          $data['image'] = $image;
        }
        catch (Exception $e) {
          $data['error'] = $e->getMessage();
        }
      }

      $view = View::factory('Json');
      $view->copyAll($data);
      echo $view->render();
      exit();
    }
    elseif (s::request()->get('formAction') == 'imagesSetCaption') {
      $pk = $this->getPrimaryKey();
      $id = s::request()->post($pk);
      $caption = s::request()->post('caption');

      $data = array($pk => $id, $this->getFieldName('caption') => $caption);

      DB::getInstance()->update($this->getTable(), $data, "$pk = :$pk")->execute($data);

      $view = View::factory('Json');
      $view->set($pk, $id);
      echo $view->render();
      exit();
    }
    elseif (s::request()->get('formAction') == 'imagesThumb') {
      $pk = $this->getPrimaryKey();
      $id = s::request()->get($pk);
      $image = DB::getInstance()->query()->from($this->getTable())->where("$pk = :$pk")->execute(array($pk => $id))->fetchRow();
      $this->outputThumb($image[$this->getFieldName('filename')], 100, 100);
      exit();
    }
  }

  public function render($row, $action)
  {
    $this->beforeRender($row, $action);

    $images = $this->loadData($row);

    foreach ($images as &$image) {
      //$image['thumb_src'] = $this->getThumb($image[$this->getFieldName('filename')], 100, 100);
      $image['image_src'] = $this->getThumb($image[$this->getFieldName('filename')]);

      $params = array($this->form->pk => $this->form->getId(), 'formAction' => 'imagesThumb', $this->getPrimaryKey() => $image[$this->getPrimaryKey()]);
      $image['thumb_src'] = s::response()->makeUrl($this->form->getRoute(), $params);
      //pre($image['thumb_src']);die();
    }

    $this->set('images', $images);

    $this->set('value', $this->getValue($row));
    $this->set('class', $this->getClass($row, $action));
    $this->set('rowClass', $this->getRowClass($row));

    $this->set('action', $action);
    $this->set('name', $this->getName());
    $this->set('title', $this->getTitle());
    $this->set('typeClass', $this->getTypeClass());
    $this->set('instanceClass', $this->getInstanceClass());
    $this->set('enabled', $this->enabled);

    $this->set('pk', $this->getPrimaryKey());

    $output = $this->getView();

    $output = $this->afterRender($output, $row, $action);

    return $output;
  }

  public function getTable()
  {
    if (empty($this->table)) {
      $this->table = $this->form->table;
    }

    return $this->table;
  }

  public function getPrimaryKey()
  {
    if (empty($this->primaryKey)) {
      $this->primaryKey = Inflector::singularize($this->getTable()) . '_id';
    }

    return $this->primaryKey;
  }

  public function getForeignKey()
  {
    if (empty($this->foreignKey)) {
      $this->foreignKey = $this->getField();
    }

    return $this->foreignKey;
  }

  public function getFieldName($name)
  {
    if (is_array($this->fields) && isset($this->fields[$name])) {
      $name = $this->fields[$name];
    }
    else {
      $name = Inflector::singularize($this->table) . '_' . $name;
    }

    return $name;
  }

  protected function loadData($row)
  {
    $pk = $this->getField();
    $fk = $this->getForeignKey();

    $id = $row[$pk];

    $data = DB::getInstance()->query()->from($this->getTable())->where("$fk = :$pk")->execute(array($pk => $id))->fetchAll();

    return $data;
  }

  protected function getThumb($file, $width = null, $height = null)
  {
    try {
      if (! file_exists($this->getFilesDir() . $file)) {
        $src = false;
      }

      if ($width && $height) {
        $thumb = $this->getThumbComponent();

        $thumb->setParam('config_cache_directory', $this->getCacheDir());
        $thumb->setParam('config_document_root', $this->getFilesDir());

        $thumb->parse($file);

        $src = $this->getCacheUrl() . '/' . $thumb->getCacheFilename($width, $height);
      }
      else {
        $src = $this->getFilesUrl() . $file;
      }
    }
    catch (Exception $e) {
      $src = false;
    }

    return $src;
  }

  protected function outputThumb($file, $width = null, $height = null)
  {
    try {
      if (! file_exists($this->getFilesDir() . $file)) {
        s::response()->redirect404();
      }

      $thumb = $this->getThumbComponent();

      $thumb->setParam('config_cache_directory', $this->getCacheDir());
      $thumb->setParam('config_document_root', $this->getFilesDir());

      $thumb->parse($file);

      $thumb->output($width, $height);
    }
    catch (Exception $e) {
      s::response()->redirect404();
    }
  }

  protected function getFilesUrl()
  {
    return s::config()->get('files_url');
  }

  protected function getCacheUrl()
  {
    return s::config()->get('files_url') . '/cache';
  }

  protected function getFilesDir()
  {
    return s::config()->get('files_dir');
  }

  protected function getCacheDir()
  {
    return s::config()->get('files_dir') . '/cache';
  }

  /**
   *
   * @return PhpThumbComponent
   */
  protected function getThumbComponent()
  {
    return Component::factory('php_thumb');
  }

}

?>